<template>
    <div>
        <Category :scene="scene"></Category>
        <div v-show="scene == 0">
            <el-card shadow="hover" :body-style="{ padding: '20px' }" style="margin-top:10px">
                <el-button type="primary" size="default" :icon="Plus" @click="addAttr" :disabled="!Categorystore.c3Id">
                    添加属性</el-button>
                <el-table border stripe :data="attrList" style="margin-top:10px">
                    <el-table-column label="序号" width="80px" type="index"></el-table-column>
                    <el-table-column label="属性名称" width="130px" prop="attrName"></el-table-column>
                    <el-table-column label="属性值列表">
                        <template #="{row,$index}">
                            <el-tag style="margin:0px 3px" class="ml-2" type="success"
                                v-for="(attrVal,index) in row.attrValueList" :key="attrVal.id">{{ attrVal.valueName
                                }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="130px">
                        <template #="{ row ,$index}">
                            <el-button type="warning" size="small" :icon="Edit" @click="updateAttr(row)" />
                            <el-button type="danger" size="small" :icon="Delete" @click="removeAttr(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <div v-show="scene == 1" style="margin-top:10px">
            <el-card shadow="hover" :body-style="{ padding: '20px' }">

                <el-form label-width="80px" :inline="true">
                    <el-form-item label="属性名">
                        <el-input placeholder="请输入属性名" clearable v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性值
                </el-button>
                <el-button size="default" @click="scene=0">取消</el-button>
                <el-table border stripe  style="margin:10px 0px" :data="attrParams.attrValueList">
                    <el-table-column label="序号" width="80px" align="center" type="index">
                    </el-table-column>
                    <el-table-column label="属性值">
                        <template #="{row,$index}">
                            <el-input :ref="(vc)=>(inputArr[$index]==vc)" clearable v-model="row.valueName"
                                v-if="row.flag" @blur="toLook(row,$index)"></el-input>
                            <div v-else @click="toEdit(row,$index)">{{row.valueName}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{row,$index}">
                            <el-button type="danger" size="small" :icon="Delete" @click="delAttrValue(row,$index)">
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" :disabled="attrParams.attrValueList.length > 0 ? false : true"
                    @click="save">保存</el-button>
                <el-button size="default" @click="scene=0">取消</el-button>
            </el-card>
        </div>
    </div>

</template>

<script lang="ts" setup>
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
import { reqAttrList, reqAddorUpdatartte, reqDeleteAttr } from '@/api/product/attr/attr'
//引入数据类型
import type {attrResponseData,attrModel,attrValueModel} from '../../../api/product/attr/model/attr'
import { watch, ref, reactive, nextTick ,onUnmounted} from 'vue'
import useCategory from '../../../stores/category'
import { ElMessage } from "element-plus";
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";
// console.log(useCategory);

let Categorystore = useCategory()
let attrList = ref<attrResponseData>([])
// 修改属性值页面的显示和隐藏
let scene = ref<number>(0)
// 拿到input
let inputArr = ref<any>([])
// 属性值返回的数据
let attrParams = reactive<attrModel>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
})
watch(() => Categorystore.c3Id, () => {
    if (Categorystore.c3Id == '') return
    getattrList()
})
const getattrList = async () => {
    let result:attrResponseData = await reqAttrList(Categorystore.c1Id, Categorystore.c2Id, Categorystore.c3Id)
    attrList.value = result
}
// 添加属性按钮
const addAttr = () => {
    scene.value = 1
    //点击添加属性按钮每一次都要情况带给服务器参数
    //情况数据:浅拷贝
    Object.assign(attrParams, {
        attrName: "",
        categoryId: Categorystore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
        categoryLevel: 3,
        attrValueList: [],
    });
}
// 添加属性值
const addAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true
    })
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus();
    })
}
const toLook = (row:attrValueModel, $index:number) => {
    if (row.valueName.trim() == '') {
        ElMessage({
            type: "warning",
            message: "亲爱的属性值不能为空",
        });
        attrParams.attrValueList.splice($index, 1)
        return
    }

    let repeat = attrParams.attrValueList.find((item) => {
        if (row != item) {
            return row.valueName === item.valueName
        }
    })
    if (repeat) {
        ElMessage({
            type: "warning",
            message: "亲爱的属性值不能重复",
        });
        //属性值数组把当前非法属性值对象干掉
        attrParams.attrValueList.splice($index, 1);
    }
    row.flag = false
}
const toEdit = (row:attrValueModel, $index:number) => {
    row.flag = true
    nextTick(() => {
        inputArr.value[$index].focus()
    })
}
// 保存按钮
const save = async () => {
    attrParams.attrValueList.forEach((item)=>{
        if(item.hasOwnProperty("flag")){
            delete item.flag
        }
    })
    try {
        await reqAddorUpdatartte(attrParams)
        scene.value = 0
        ElMessage({
            type: "success",
            message: "添加成功",
        });
        getattrList()
    } catch (error) {
        ElMessage({
            type: "warning",
            message: "添加失败",
        });
    }
}

// 删除属性值按钮
const delAttrValue = async (row:attrValueModel, $index:number) => {
   
    attrParams.attrValueList.splice($index, 1)
}

// 修改属性
const updateAttr = (row: attrModel) => {
    scene.value = 1
    Object.assign(attrParams, _.cloneDeep(row))
}
// 删除属性
const removeAttr = async (row: any) => {
    try {
        await reqDeleteAttr(row.id)
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        getattrList()

    } catch (error) {
        ElMessage({
            type: "warning",
            message: "删除失败",
        });
    }
}
//组件销毁钩子
onUnmounted(() => {
  //组件销毁的时候。情况仓库里面的数据
  Categorystore.c1Id = "";
  Categorystore.c2Id = "";
  Categorystore.c3Id = "";
  Categorystore.C1List = [];
  Categorystore.C2List = [];
  Categorystore.C3List = [];
});
</script>

<style scoped>

</style>